package com.wyj.databinding

import android.content.Context
import androidx.databinding.Observable
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.qmuiteam.qmui.util.QMUIReflectHelper
import kotlin.reflect.KMutableProperty0

object DataBindingHelper {

    @JvmStatic
    fun convert2LiveData(context: Context, obj: Any, fieldName: String): MutableLiveData<String?> {
        val newFieldName = fieldName[0].toUpperCase() + fieldName.substring(1)
        return convert2LiveData(context, obj, "get$newFieldName", "set$newFieldName")
    }

    @JvmStatic
    fun convert2LiveData(context: Context, obj: Any, getFunctionName: String, setFunctionName: String): MutableLiveData<String?> {
        val field = MutableLiveData<String?>()
        field.value = QMUIReflectHelper.invokeMethod<String>(obj, getFunctionName)
        (context as? LifecycleOwner)?.let {
            field.observe(it, {
                QMUIReflectHelper.invokeMethod<Void>(obj, setFunctionName, arrayOf(String::class.java), arrayOf(it))
            })
        }
        return field
    }

    @JvmStatic
    fun convert2ObservableField(obj: Any, fieldName: String): ObservableField<String?> {
        val newFieldName = fieldName[0].toUpperCase() + fieldName.substring(1)
        return convert2ObservableField(obj, "get$newFieldName", "set$newFieldName")
    }

    @JvmStatic
    fun convert2ObservableField(prop: KMutableProperty0<String?>): ObservableField<String?> {
        val field = ObservableField<String?>()
        field.set(prop.get())
        field.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                prop.set(field.get())
            }
        })
        return field
    }

    @JvmStatic
    fun convert2ObservableField(obj: Any, getFunctionName: String, setFunctionName: String): ObservableField<String?> {
        val field = ObservableField<String?>()
        field.set(QMUIReflectHelper.invokeMethod<String>(obj, getFunctionName))
        field.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                QMUIReflectHelper.invokeMethod<Void>(obj, setFunctionName, arrayOf(String::class.java), arrayOf(field.get()))
            }
        })
        return field
    }
}